package com.caih.contacts.service.impl;

import com.caih.contacts.entity.Employees;
import com.caih.contacts.entity.Result;
import com.caih.contacts.service.WeiXinDepartmentService;
import com.caih.contacts.service.WeiXinEmployeesService;
import com.caih.contacts.util.AccessToken;
import com.caih.contacts.util.WeiXinRequest;
import com.caih.contacts.util.WeiXinSercret;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class WeiXinEmployeesServiceimpl implements WeiXinEmployeesService {

    private  static  String createUser_url="https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=ACCESS_TOKEN";
    private  static  String deleteEmp_url="https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=ACCESS_TOKEN&userid=USERID";
    private  static  String updateEmp_url="https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=ACCESS_TOKEN";
    private  static  String batchdeleteEmp_url="https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=ACCESS_TOKEN";

    /**
     * 微信端保存员工
     * @param employees
     * @param accessToken
     * @return
     */
    @Override
    public Result<Employees> createE(Employees employees,String accessToken) {
        //String access_token = accessToken;
        Gson gson = new Gson();
        String jsonU1 = gson.toJson(employees);
        System.out.println("jsonU1"+jsonU1);
        //System.out.println(accessToken);
        //uri = createUser_url+accessToken;
        createUser_url=createUser_url.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = WeiXinRequest.httpsRequest(createUser_url,"POST",employees.toString());

        Result<Employees> result = new Result<>();
        result.setCode(jsonObject.getInt("errcode"));
        result.setMessage(jsonObject.getString("errmsg"));
        result.setData(employees);
        return result;

    }

    /**
     * 微信端更新员工
     * @param employees
     * @param accessToken
     * @return
     */
    @Override
    public Result<Employees> updateE(Employees employees,String accessToken) {
        Gson gson=new Gson();
        String jsonui=gson.toJson(employees);
        System.out.println("jsonui"+jsonui);
        updateEmp_url=updateEmp_url.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject= WeiXinRequest.httpsRequest(updateEmp_url,"POST",jsonui);
        //System.out.println("jsonobject"+jsonObject.toString());
        Result<Employees> result = new Result<>();

        if(jsonObject!=null){
            if(jsonObject.getInt("errcode")!=0){
                //  log.error("更新成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                result.setCode(jsonObject.getInt("errcode"));
                result.setMessage(jsonObject.getString("errmsg"));
            }
            else{
                result.setCode(jsonObject.getInt("errcode"));
                result.setMessage(jsonObject.getString("errmsg"));
                result.setData(employees);
            }
        }
        return result;

    }

    /**
     * 微信端删除员工
     * @param id
     * @param accessToken
     * @return
     */
    @Override
    public Result<String> deleteE(String id,String accessToken) {
        //1.获取请求的url
        deleteEmp_url=deleteEmp_url.replace("ACCESS_TOKEN", accessToken).replace("USERID",id);
        //2.调用接口，发送请求，删除成员
        JSONObject jsonObject = WeiXinRequest.httpsRequest( deleteEmp_url, "GET", null);
        System.out.println("jsonObject:"+jsonObject.toString());
        Result<String> result= new Result<>();
        // 如果请求成功
        result.setCode(jsonObject.getInt("errcode"));
        result.setMessage(jsonObject.getString("errmsg"));
        if (jsonObject.getInt("errcode")==0){
            result.setData("删除成功");
        }else{
            result.setData("删除失败");
        }
        return result;

    }

    /**
     * 微信端批量删除
     * @param useridList
     * @param accessToken
     * @return
     */
   @Override
    public Result<String> batchDeleteE(List<String> useridList,String accessToken) {

        Map<String, Object> content = new HashMap<>();
        Result<String> result = new Result<>();
        content.put("useridlist", useridList);

        Gson gson=new Gson();
        String useridlist=gson.toJson(content);
        System.out.println(useridlist);

        //2.获取请求的url
        batchdeleteEmp_url=batchdeleteEmp_url.replace("ACCESS_TOKEN", accessToken);

        //3.调用接口，发送请求，创建成员
        JSONObject jsonObject = WeiXinRequest.httpsRequest(batchdeleteEmp_url, "GET", useridlist);
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                result.setCode(jsonObject.getInt("errcode"));
                result.setMessage(jsonObject.getString("errmsg"));
                result.setData("批量删除成员失败");
            } else{
                result.setCode(jsonObject.getInt("errcode"));
                result.setMessage(jsonObject.getString("errmsg"));
                result.setData("批量删除成员成功");
            }
        }
        return result;
    }

    /**
     * 获取Access_Token保存Cache
     * @return
     */
    @Override
    @Cacheable(value = "accessToken")
    public  AccessToken getAccessToken() {
        System.out.println("调用此方法");
        return WeiXinRequest.getAccessToken(WeiXinSercret.corpId,WeiXinSercret.corpSecret);
    }

    /**
     * 刷新Cache
     * @return
     */
    @Override
    @Scheduled(fixedRate = 3600000)
    @CachePut(value = "accessToken")
    public AccessToken updateAccessToken() {
        System.out.println("更新方法");
        return WeiXinRequest.getAccessToken(WeiXinSercret.corpId,WeiXinSercret.corpSecret);
    }
}
